<script lang="ts" setup>
import { ref } from 'vue'
import { getVideoOrdersByPage, deleteOrder, videoMockPay } from '@/services/videoDiagnose'
import dayjs from 'dayjs'
import { onReachBottom, onShow } from '@dcloudio/uni-app'
import { useMemberStore } from '@/stores'
import { generateRandomDigitString } from '@/utils/randomString'

const page = ref(1)
const length = ref(50)
const json = ['进入问诊室', '进入问诊室', '已结束']
const isLastPage = ref(false)
const doctorImg = `http://114.132.57.246:9000/hospital/patient-wx/pic/pic-2.png`

const list = ref<any[]>([])
const loadDataList = () => {
  let data = {
    page: page.value,
    length: length.value,
  }
  getVideoOrdersByPage(data).then((res) => {
    console.log(res)
    let result = res.result
    if (result.list == null || result.list.length == 0) {
      isLastPage.value = true
      page.value = page.value - 1
      uni.showToast({
        icon: 'none',
        title: '已经到底了',
      })
    } else {
      for (let one of result.list) {
        // console.log(one)
        one.expectStartShort = dayjs(one.expectStart).format('HH:mm')
        one.expectEndShort = dayjs(one.expectEnd).format('HH:mm')
        one.outTradeNoShort = one.outTradeNo.substr(0, 15) + '…'
        list.value.push(one)
      }
    }
  })
}

const copyOutTradeNoHandle = (outTradeNo: string) => {
  uni.setClipboardData({
    data: outTradeNo,
    showToast: false,
    success: function () {
      uni.showToast({
        icon: 'success',
        title: '已复制订单号',
      })
    },
  })
}

const registerHandle = () => {
  const memberStore = useMemberStore()
  if (memberStore.profile?.token && memberStore.profile?.token !== '') {
    uni.navigateTo({
      url: '/registration/notice/notice',
    })
  } else {
    uni.showToast({
      icon: 'none',
      title: '请先登录',
      complete: () => {
        uni.navigateTo({
          url: '/pages/mine/mine',
        })
      },
    })
  }
}

const deleteHandle = (id: number) => {
  uni.showModal({
    title: '提示信息',
    content: '是否删除该订单',
    confirmText: '删除',
    cancelText: '取消',
    complete: (res) => {
      if (res.confirm) {
        deleteOrder({ id }).then((res) => {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1500,
          })
          setTimeout(() => {
            list.value = []
            loadDataList()
          }, 1000)
        })
      }
    },
  })
}

const handleRepay = (id: number, outTradeNo: string) => {
  uni.showModal({
    title: '提示信息',
    content: '确认挂号并支付？',
    confirmText: '模拟支付',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        let data = {
          outTradeNo: outTradeNo,
          transactionId: generateRandomDigitString(dayjs().format('YYYYMMDD'), 12),
        }
        await videoMockPay(data).then((res) => {
          if (res.result) {
            uni.showToast({
              icon: 'success',
              title: '付款成功',
            })
            setTimeout(() => {
              uni.navigateTo({
                url: `/video_diagnose/prepare_diagnose/prepare_diagnose?videoDiagnoseId=${videoDiagnoseId}&expectStart=${expectStart}&expectEnd=${expectEnd}&doctorId=${doctorId}`,
              })
            }, 1500)
          } else {
            uni.showToast({
              icon: 'none',
              title: '付款异常，请联系客服',
            })
          }
        })
      } else if (res.cancel) {
        uni.showToast({
          icon: 'none',
          title: '取消支付',
        })
      }
    },
  })
}

const enterHandle = (id: number, expectStart: string, expectEnd: string, doctorId: number) => {
  uni.navigateTo({
    url: `/video_diagnose/prepare_diagnose/prepare_diagnose?videoDiagnoseId=${id}&expectStart=${expectStart}&expectEnd=${expectEnd}&doctorId=${doctorId}`,
  })
}

onReachBottom(() => {
  if (isLastPage.value) {
    return
  }
  page.value = page.value + 1
  loadDataList()
})

onShow(() => {
  const memberStore = useMemberStore()
  if (memberStore.profile?.token && memberStore.profile?.token !== '') {
    page.value = 1
    list.value = []
    isLastPage.value = false
    loadDataList()
  }
})
</script>

<template>
  <view>
    <view class="banner">
      <image :src="doctorImg" mode="widthFix"></image>
      <view>
        <view class="row-1">
          <text class="title">视频问诊</text>
          <text class="remark">接诊快</text>
        </view>
        <view class="row-2">
          <view class="btn" @tap="registerHandle">立即挂号</view>
        </view>
        <view class="row-3">查找名医，远程诊断，预约挂号，不再等待</view>
      </view>
    </view>
    <uni-swipe-action>
      <uni-swipe-action-item v-for="one of list" :key="one">
        <view class="order">
          <view class="row">
            <view @longtap="copyOutTradeNoHandle(one.outTradeNo)">
              <u-icon
                :label="`订单编号：${one.outTradeNoShort}`"
                color="#a0a0a0"
                labelColor="#a0a0a0"
                size="20"
                name="order"
              ></u-icon>
            </view>
            <view>
              <text
                class="status blue"
                v-if="(one.status === 1 || one.status === 2) && one.paymentStatus === 2"
                @tap="enterHandle(one.id, one.expectStart, one.expectEnd, one.doctorId)"
              >
                {{ json[one.status - 1] }}
              </text>
              <text class="status" v-if="one.status === 3">
                {{ json[one.status - 1] }}
              </text>
            </view>
          </view>
          <view class="row">
            <view>
              <text class="doctor-name">{{ one.doctorName }}</text>
              <text class="job">（{{ one.job }}）</text>
            </view>
            <view>
              <text class="unit">￥</text>
              <text class="amount">{{ one.amount }}</text>
            </view>
          </view>
          <view class="row">
            <u-icon
              :label="`${one.subName}（${one.expectStartShort} ~ ${one.expectEndShort}）`"
              color="#555"
              labelColor="#555"
              size="18"
              name="server-fill"
            ></u-icon>
          </view>
          <view class="row">
            <view class="create-time">
              <u-icon
                :label="one.createTime"
                color="#a0a0a0"
                labelColor="#a0a0a0"
                size="20"
                name="calendar-fill"
                top="0"
              ></u-icon>
            </view>
            <view
              class="btn green"
              v-if="one.paymentStatus == 1"
              @tap="handleRepay(one.id, one.outTradeNo)"
              >未付款</view
            >
            <view class="btn orange" v-if="one.paymentStatus == 2">已付款</view>
            <view class="btn gray" v-if="one.paymentStatus == 3">已关闭</view>
          </view>
        </view>
        <!-- 右侧删除按钮 -->
        <template #right>
          <view class="cart-swipe-right">
            <button class="button delete-button" @tap="deleteHandle(one.id)">删除</button>
          </view>
        </template>
      </uni-swipe-action-item>
    </uni-swipe-action>
    <view v-if="list.length == 0">
      <u-empty
        mode="order"
        text="没有问诊挂号记录"
        icon="http://cdn.uviewui.com/uview/empty/order.png"
      ></u-empty>
    </view>
  </view>
</template>

<style lang="less">
@import url('registration_list.less');
.cart-swipe-right {
  margin-top: 25rpx;
  .button {
    border-radius: 0;
    height: 100%;
    background-color: #fa3534;
    color: #fff;
    line-height: 316rpx;
  }
}
</style>
